/****************************
 * 常用基本－公共函数库
 ****************************/

 //合并自定义方法
var myCommonFun = require("../../common/commonFunc")
for(var k in myCommonFun){
	exports[k] = myCommonFun[k];
}

(function () {

	/**
	 * MD5加密函数
	 **/
	exports.md5 = function (data) {
		var Buffer = require("buffer").Buffer;
		var buf = new Buffer(data);
		var str = buf.toString("binary");
		var crypto = require("crypto");
		return crypto.createHash("md5").update(str).digest("hex");
	};


	/**
	 * 将字符串分割成数组
	 **/
	exports.strTransformArr = function (str) {
		var tmpArr = new Array();
		var tmpStr = str.split(",")[0].split("|");
		for (i in tmpStr) {

			tmpArr.push(tmpStr[i]);
		}
		return tmpArr;
	};


	/**
	 * 将字符串中的内容,匹配数组中的每个内容,如果存在就替换成指定字符
	 **/
	exports.filterStr = function (str, arr, character) {

		var str = str;
		for (var i = 0; i < arr.length; i++) {
			str = str.replace(arr[i], character);
		}
		return str;
	};


	/**
	 * 获取当前的时间
	 * 参数1:如果为true就获取毫秒，为false获取秒
	 **/
	exports.nowTime = function (timeResult) {

		var timeRs;
		if (timeResult) {
			timeRs = new Date().getTime();
		} else {
			timeRs = parseInt(new Date().getTime() / 1000);
		}
		return timeRs;
	};

	/**
	 * 获取6位随机验证码
	 * @returns {string} 验证码
	 */
	exports.getVerificationCode = function () {
		var num = "";
		for (var i = 0; i < 6; i++) {
			num = num + Math.floor(Math.random() * 10);
		}
		return num;
	};

	/**
	 * 解析restful参数
	 */
	exports.parseRestFulParams = function (paramsURL) {

		var restFulArr = paramsURL.split("/");

		//判断是否为键值对的格式
		if (restFulArr.length % 2 != 0) {
			return false;
		}

		//将参数记录为JSON形势
		var jsonParams = {};
		if (restFulArr.length > 0) {
			for (var i = 0; i < restFulArr.length; i++) {

				//判断key是否为数字
				if (!isNaN(restFulArr[i])) {
					return false;
				}

				//保存参数信息
				jsonParams[restFulArr[i]] = restFulArr[i + 1];
				i++;
			}
		}

		return jsonParams;

	};

	/**
	 * 将JSON参数组装成RESTFUL格式
	 */
	exports.JsonTransformRestFulParams = function (json) {

		var restfulStr = "";
		for (k in json) {
			restfulStr += "/" + k + "/" + json[k] + "/";
		}

		return restfulStr;

	};


	/**
	 * 去除字符串最后一位
	 */
	exports.takeStrLast = function (str) {
		return str.substr(0, str.length - 1);  
	};


	/**
	 * 判断一个对象是否为空
	 */
	exports.isNullObj = function (obj) {
		for (var i in obj) {
			if (obj.hasOwnProperty(i)) {
				return false;
			}
		}
		return true;
	};


	/**
	 * 获取JSON数据中所有KEY组成的数组
	 */
	exports.getJsonKeyArray = function (obj) {

		var tempArr = [];

		if (obj == undefined) {
			return tempArr;
		}

		for (var k in obj) {
			tempArr.push(k);
		}
		return tempArr;

	};


	/**
	 * 获取两个数组的交集
	 */
	exports.intersect = function(){  
		var result = new Array();
            var obj = {};
            for (var i = 0; i < arguments.length; i++) {
                for (var j = 0; j < arguments[i].length; j++) {
                    var str = arguments[i][j];
                    if (!obj[str]) {
                        obj[str] = 1;
                    }
                    else {
                        obj[str]++;
                        if (obj[str] == arguments.length)
                        {
                            result.push(str);
                        }
                    }
                }
            }
            return result;
   };

	/**
	 * 获取两个数组的差集
	 */
	exports.minus = function (arr1, arr2) {
		var result = new Array();
		var obj = {};
		for (var i = 0; i < arr2.length; i++) {
			obj[arr2[i]] = 1;
		}

		for (var j = 0; j < arr1.length; j++) {
			if (!obj[arr1[j]])
			{
				obj[arr1[j]] = 1;
				result.push(arr1[j]);
			}
		}

		return result;
	}

	/**
	 * 数组中根据某个key排序
	 */
	exports.compare = function (key) {
		return function (obj1, obj2) {
			var val1 = obj1[key],
				val2 = obj2[key]
			return val1 <= val2 ? -1 : 1
		}
	}



	/*
	 * 生成验证码
	 */
	exports.createCaptcha = function () {

		//导入验证码类库
		var ccap = require('ccap');

		//验证码格式设置
		var ccapObj = ccap({
			width: 106,
			height: 50,
			offset: 25,
			quality: 100,
			generate: function () {
				return common.getRandom(4);
			}
		});

		var ary = ccapObj.get();

		//验证码内容
		var txt = ary[0];

		//验证码图片
		var buf = ary[1];
		return [buf, txt];

	}

	/*
	 * 根据传递长度,获取随相应长度的随机数
	 */
	exports.getRandom = function (length) {
		var num = "";
		for (var i = 0; i < length; i++) {
			num = num + Math.floor(Math.random() * 10);
		}
		return num;
	}

	/*
	 * 获取当前年月日 格式 2012-12-12
	 */
	exports.getNowFormatDate = function () {

		var date = new Date();
		var seperator1 = "-";
		var seperator2 = ":";
		var year = date.getFullYear();
		var month = date.getMonth() + 1;
		var strDate = date.getDate();
		if (month >= 1 && month <= 9) {
			month = "0" + month;
		}
		if (strDate >= 0 && strDate <= 9) {
			strDate = "0" + strDate;
		}
		var currentdate = year + seperator1 + month + seperator1 + strDate;
		return currentdate;

	}

	/*
	 * 阻塞测试
	 */
	exports.sleep = function (milliSeconds) {
		var startTime = new Date().getTime();
		while (new Date().getTime() < startTime + milliSeconds);
	}

	/*
	 * 获取当前年月日
	 */
	exports.getNowFormatDate = function () {
		var date = new Date();
		var seperator1 = "-";
		var seperator2 = ":";
		var month = date.getMonth() + 1;
		var strDate = date.getDate();
		if (month >= 1 && month <= 9) {
			month = "0" + month;
		}
		if (strDate >= 0 && strDate <= 9) {
			strDate = "0" + strDate;
		}
		var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate;
		return currentdate;
	}

	/*
	 * 判断数组中是否包含某个元素
	 */
	exports.containsArr = function (arr, obj) {
		var i = arr.length;
		while (i--) {
			if (arr[i] === obj) {
				return true;
			}
		}
		return false;
	}

	/*
	 * 合并两个对象
	 */
	exports.mergeJsonObject = function(jsonbject1, jsonbject2) {
		
		var resultJsonObject = {};

		for (var attr in jsonbject1.API) {
		  resultJsonObject[attr] = jsonbject1.API[attr];
		}
		for (var attr in jsonbject2.API) {
		  resultJsonObject[attr] = jsonbject2.API[attr];
		}
		return resultJsonObject;
	}

	/*
	 * 下载远程文件
	 */
	exports.downLoadFile = function(src,dsc,cb){

		var fs = require("fs");
        var writeStream = fs.createWriteStream(dsc);
        var readStream = request(src);
        readStream.pipe(writeStream);
        readStream.on('end', function () {});
        readStream.on('error', function (err) {
			cb(false,err);
		});
        writeStream.on("finish", function () {
            writeStream.end();
            cb(true);
        });
	}

	/*
	 * 解压
	 */
	exports.unZipAction = function(src,dsc,cb){

		//解压文件
		var unzip = require("unzip");

		var fs = require("fs");

		fs.createReadStream(src).pipe(unzip.Extract({ path: dsc }));

		cb();

	},

	//删除文件
	exports.unlinkFile = function(path,cb){

		var fs = require("fs");

		fs.unlink(path,function(error){
			if(error){
				cb(false)
			}else{
				cb(true)
			}
		})
	},

	//删除目录及目录中的文件
	exports.delDir = function(path){

		var fs = require("fs");

		let files = [];
		if(fs.existsSync(path)){
			files = fs.readdirSync(path);
			files.forEach((file, index) => {
				let curPath = path + "/" + file;
				if(fs.statSync(curPath).isDirectory()){
					this.delDir(curPath);
				} else {
					fs.unlinkSync(curPath);
				}
			});
			fs.rmdirSync(path);
		}
	},

	//对象数组去重
	exports.ObjectArrDistinct = function(data,k){
		var result = [];
		var obj = {};
		for(var i =0; i<data.length; i++){
			if(!obj[data[i][k]]){
				result.push(data[i]);
				obj[data[i][k]] = true;
			}
		}
		return result;
	},

	//SSH2执行命令
	exports.Ssh_exec = function(command,params,cb){
		
		//获取ssh连接对象
		var SSHClient = require('ssh2').Client;

		//实例化连接对象
		var sshConnection = new SSHClient();

		var resultStr = "";

		var resultData = [];

		//监听连接状态
		sshConnection.on('ready', function () {


			sshConnection.exec(command, function (err, stream) {
	
				//监听结束
				stream.on('close', function (code, signal) {
	
					sshConnection.end();
	
					resultStr = resultData.toString();
	
					//字符串替换操作
					replaceLinuxStr("\u001b[32m","<font color='green'>")
					replaceLinuxStr("\u001b[37m","<font color='#ccc'>")
					replaceLinuxStr("\u001b[90m","<font color='gray'>")
					replaceLinuxStr("\u001b[33m","<font color='orange'>")
					replaceLinuxStr("\u001b[35m","<font color='magenta'>")
					replaceLinuxStr("\u001b[31m","<font color='red'>")
					replaceLinuxStr("\n","<br/>")
					replaceLinuxStr("\u001b[39m","</font>")
					
					cb(resultStr)
					
	
				}).on('data', function (data) {
					
					resultData.push(data)
	
				}).stderr.on('data', function (data) {
	
					resultData.push(data)
	
				});
	
			})
	
		}).connect({
	
			host: params.server_ip,
			port: config.sshConfig.port,
			username: config.sshConfig.user,
			password: config.sshConfig.pass,
	
		})
	
		function replaceLinuxStr(str,rep){
	
			resultStr = resultStr.replace(str,rep);
			if(resultStr.indexOf(str) != -1){
				replaceLinuxStr(str,rep)
			}
	
		}
	}

}).call(this);

